<script setup>
import { addRole, deleteRole, updateRoleApi, queryRole } from '@/api/system/role.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, ArrowDown } from '@element-plus/icons-vue'
import { usePagination } from '@/hooks/usePagination'
import AddRole from './components/AddRole.vue'
import { useUserStore } from '@/store/modules/user'
import MenuAuthority from './components/MenuAuthority.vue'
import AppAuthority from './components/AppAuthority.vue'
import dayjs from 'dayjs'
// 获取store变量
const userStore = useUserStore()

const loading = ref(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const addRoleRef = ref(null)
const pageData = reactive({
  editingId: '',
  isShowAddDialog: false,
  isShowAuthorityDialog: false,
  menuList: []
})

const createRole = (record) => {
  addRole(record)
    .then(() => {
      ElMessage.success('新增成功')
      pageData.isShowAddDialog = false
      getTableData()
    })
    .finally(() => {
      submitBtnLoading.value.submitBtnLoading = false
    })
}

const updateRole = (record) => {
  updateRoleApi(record)
    .then(() => {
      ElMessage.success('修改成功')
      pageData.isShowAddDialog = false
      getTableData()
    })
    .finally(() => {
      submitBtnLoading.value.submitBtnLoading = false
    })
}

const toAddRole = () => {
  pageData.editingId = ''
  pageData.isShowAddDialog = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`正在删除角色：${row.name}，确认删除？`, 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteRole(row._id).then(() => {
      ElMessage.success('删除成功')
      getTableData()
    })
  })
}

const handleUpdate = (row) => {
  pageData.editingId = row._id
  pageData.isShowAddDialog = true
}

const tableData = ref([])
const searchFormRef = ref()
const searchData = reactive({
  name: ''
})
const getTableData = () => {
  loading.value = true
  queryRole(searchData, {
    currentPage: (paginationData.currentPage - 1) * paginationData.pageSize,
    size: paginationData.pageSize
  })
    .then((res) => {
      paginationData.total = parseInt(res.data.total)
      tableData.value = res.data.data
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const handleMenuAuthority = (row) => {
  pageData.editingId = row._id
  pageData.menuList = row.menuIdList
  pageData.isShowAuthorityDialog = true
}

const updateAuthority = () => {
  pageData.isShowAuthorityDialog = false
  appData.isShowAuthorityDialog = false
  ElMessage.success('修改成功')
}
const appData = reactive({
  editingId: '',
  isShowAuthorityDialog: false
})
const handleAppAuthority = (row) => {
  appData.editingId = row._id
  appData.isShowAuthorityDialog = true
}
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <div v-hasPermi="['sysRole:post:findPage']" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="searchData.name" placeholder="请输入角色名称" maxlength="30" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" plain :icon="Plus" @click="toAddRole">新增角色</el-button>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" max-height="64vh">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="name" label="角色名称" align="center">
            <template #default="scope">
              <!-- <router-link :to="{ path: '/system/roleLink', query: { id: scope.row.id } }" class="text-blue-600"> -->
              {{ scope.row.name }}
              <!-- </router-link> -->
            </template>
          </el-table-column>
          <el-table-column prop="permissionChar" label="权限字符" align="center" />
          <!-- <el-table-column prop="status" label="状态" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.status === 0" type="success" effect="plain">启用</el-tag>
              <el-tag v-else type="danger" effect="plain">停用</el-tag>
            </template>
          </el-table-column> -->
          <!-- <el-table-column prop="createTime" label="创建时间" align="center">
            <template #default="scope">
              {{ scope.row.createTime ? dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') : '' }}
            </template>
          </el-table-column> -->
          <el-table-column fixed="right" label="操作" width="250" align="center">
            <template #default="scope">
              <div class="flex items-center">
                <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
                <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
                <el-button type="primary" text bg size="small" @click="handleMenuAuthority(scope.row)">
                  菜单权限
                </el-button>
                <!-- <el-button
                  type="primary"
                  text
                  bg
                  size="small"
                  @click="handleMenuAuthority(scope.row)"
                >
                  菜单权限
                </el-button> -->
                <!-- <el-dropdown class="operation-more">
                  <span class="el-dropdown-link">
                    更多
                    <el-icon class="el-icon--right">
                      <arrow-down />
                    </el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="handleMenuAuthority(scope.row)">
                        <div class="dropdown-item">菜单权限</div>
                      </el-dropdown-item>
                      <el-dropdown-item @click="handleAppAuthority(scope.row)">
                        <div class="dropdown-item">应用权限</div>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown> -->
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="flex justify-end">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :small="true"
        />
      </div>
    </div>
    <AddRole
      ref="addRoleRef"
      v-model:visible="pageData.isShowAddDialog"
      :id="pageData.editingId"
      @create="createRole"
      @update="updateRole"
    />
    <MenuAuthority
      v-model:visible="pageData.isShowAuthorityDialog"
      :menuList="pageData.menuList"
      :id="pageData.editingId"
      @sure="updateAuthority"
      @update="getTableData"
    />
    <AppAuthority v-model:visible="appData.isShowAuthorityDialog" :id="appData.editingId" @sure="updateAuthority" />
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}
.table-wrapper {
  margin-bottom: 20px;
}
.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  :deep(.el-button) {
    padding: 6px 12px;
  }
}
.operation-more {
  margin-left: 12px;
  font-size: 12px;

  .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
  }
}
:deep(.el-dropdown-menu__item) {
  padding: 0;
}
.dropdown-item {
  padding: 5px 16px;
}
</style>
